#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
短视频下载器 Web版 - 主入口文件
支持独立部署和与桌面端共存
"""

import sys
import os
import shutil
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import uvicorn

# 添加父目录到路径，以便导入原有模块
current_dir = Path(__file__).parent
parent_dir = current_dir.parent
sys.path.insert(0, str(parent_dir))

def setup_web_environment():
    """设置Web版本的运行环境"""
    # 确保必要的目录存在
    required_dirs = ['cookies', 'logs', 'secure_config', 'static', 'templates']
    for dir_name in required_dirs:
        dir_path = current_dir / dir_name
        if not dir_path.exists():
            dir_path.mkdir(parents=True, exist_ok=True)

    # 复制桌面端的核心模块到web版本（如果不存在）
    core_files = [
        'config.py', 'downloader_core.py', 'cookie_manager.py',
        'security_manager.py', 'logger_manager.py', 'exceptions.py'
    ]

    for file_name in core_files:
        src_file = parent_dir / file_name
        dst_file = current_dir / file_name
        if src_file.exists() and not dst_file.exists():
            shutil.copy2(src_file, dst_file)
            print(f"✅ 已复制核心模块: {file_name}")

# 设置环境
setup_web_environment()

# 导入模块化组件
try:
    from handlers.websocket_handler import websocket_endpoint, manager
    from api.download_routes import router as download_router, set_manager, set_main_loop
except ImportError as e:
    print(f"❌ 导入模块失败: {e}")
    print("请确保所有必要的文件都存在")
    sys.exit(1)

# 创建FastAPI应用
app = FastAPI(
    title="短视频下载器 Web版", 
    version="2.1.0",
    description="完全复刻GUI功能的Web版本"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory=str(current_dir / "static")), name="static")

# 设置WebSocket管理器
set_manager(manager)

# 注册API路由
app.include_router(download_router, prefix="/api")

# WebSocket端点
app.websocket("/ws/{client_id}")(websocket_endpoint)

@app.get("/", response_class=HTMLResponse)
async def root():
    """主页 - 返回HTML模板"""
    try:
        template_path = current_dir / "templates" / "index.html"
        with open(template_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
        return HTMLResponse(content=html_content)
    except FileNotFoundError:
        return HTMLResponse(content="""
        <html>
            <head><title>错误</title></head>
            <body>
                <h1>模板文件未找到</h1>
                <p>请确保 templates/index.html 文件存在</p>
            </body>
        </html>
        """, status_code=500)

if __name__ == "__main__":
    print("📱 主界面: http://localhost:8000")
    print("📚 API文档: http://localhost:8000/docs")
    
    # 设置事件循环
    import asyncio
    
    # 启动时设置事件循环
    async def setup_app():
        loop = asyncio.get_running_loop()
        set_main_loop(loop)
    
    # 创建启动事件处理
    @app.on_event("startup")
    async def startup_event():
        await setup_app()
    
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
